package ejb;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import managedbean.ShowClientMBean;
import jpa.CustomerJPA;
import jpa.OrderJPA;
import jpa.OrderdetailJPA;
import jpa.OrderstatusJPA;
import jpa.PetJPA;
import jpa.ShippingAddressJPA;
import jpa.ShoppingCart;
import jpa.StatusJPA;

/**
 * EJB Session Bean Class of example "Practical Case Study JEE"
 */
@Stateless
public class OrderFacadeBean implements OrderFacadeRemote {
	
	//Persistence Unit Context
	@PersistenceContext(unitName="PracticalCase") 
	private EntityManager entman;
	ShippingAddressJPA sa=new ShippingAddressJPA();
		
	
	@Override
	public OrderJPA order(ShoppingCart shoopingCart) {
		// TODO Auto-generated method stub
		OrderJPA order = null;
		try {
			order = newOrder(shoopingCart);
			order.setShippingaddress(order.getcustomer().getShippingAddress());
			entman.persist(order);
			return order;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return order;
	}

	@Override
	public OrderJPA order(ShoppingCart shoopingCart, ShippingAddressJPA shipping) {
		// TODO Auto-generated method stub
		OrderJPA order = null;

		try {
			Integer idShipping=entman.createQuery("SELECT MAX(s.id) FROM ShippingAddressJPA s",Integer.class).getSingleResult();
			shipping.setid(idShipping+1);
			entman.persist(shipping);
			sa=shipping;
			order = newOrder(shoopingCart);
			order.setShippingaddress(shipping);
			entman.persist(order);
			return order;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return order;
		
	}

	public OrderJPA newOrder(ShoppingCart shoopingCart) throws Exception
	{
		float totalamount=0;
		int numlin=1;
		TypedQuery<OrderstatusJPA> query =  entman.createQuery("FROM OrderstatusJPA os WHERE os.orderstatus = ?1", OrderstatusJPA.class).setParameter(1, "Pending payment");
		OrderstatusJPA os=query.getSingleResult();
	
		//Client al que es creara la comanda, caldra sustituir aquesta part pel dni de l'usuari connectat
		CustomerJPA customer =shoopingCart.getCustomer();
		
		//Obtencio de l'ultim numero d'ordre que s'ha creat
		Integer idOrder=entman.createQuery("SELECT MAX(o.id) FROM OrderJPA o",Integer.class).getSingleResult();
		Collection<OrderdetailJPA> odl = new ArrayList<OrderdetailJPA>();
		Collection<PetJPA> pl=shoopingCart.getPets();

		//Calcul del preu total de la comanda
		for (Iterator<PetJPA> iter = pl.iterator(); iter.hasNext();){
			PetJPA pet= (PetJPA) iter.next();
			totalamount=totalamount+pet.getPrice();
		}

		//Creacio de l'ordre
		OrderJPA order= new OrderJPA(idOrder+1,customer,totalamount,os,sa);
		
		//Obtencio status=Sold per canviar l'estat dels animals
		TypedQuery<StatusJPA> query1 =  entman.createQuery("FROM StatusJPA s WHERE s.status = ?1", StatusJPA.class).setParameter(1, "Sold");
		StatusJPA s=query1.getSingleResult();
		
		//Creacio de l'Ordredetail
		for (Iterator<PetJPA> iter = pl.iterator(); iter.hasNext();){
			PetJPA pet= (PetJPA) iter.next();
			pet.setStatus(s);
			entman.merge(pet);
			OrderdetailJPA od = new OrderdetailJPA(order,numlin,pet);
			odl.add(od);
			numlin=numlin+1;
		}
		order.setOrderdetail(odl);
		return order;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<?> findAllOrders() {
		// TODO Auto-generated method stub
		Collection<OrderJPA> allOrders=null;
		try
		{
		allOrders = entman.createQuery("from OrderJPA").getResultList();
		}catch (PersistenceException e) {
			System.out.println(e);
		} 
		return allOrders;

	}

	@Override
	public OrderJPA findOrdersById(int id) {
		// TODO Auto-generated method stub

		OrderJPA order=null;
		try
		{
		@SuppressWarnings("unchecked")
		Collection<OrderJPA> orders = entman.createQuery("FROM OrderJPA o WHERE o.id = ?1").setParameter(1, id).getResultList();

			for (Iterator<OrderJPA> iter = orders.iterator(); iter.hasNext();){
				order = (OrderJPA) iter.next();
			}
		}catch (PersistenceException e) {
			System.out.println(e);
		} 	
		 		
		return order;
		
	}

	@Override
	public void cancelOrder(OrderJPA order) {
		// TODO Auto-generated method stub
		if (order.getOrderstatus().getOrderstatus().equals("Shipped")==false) {
		OrderstatusJPA os=new OrderstatusJPA("Canceled");
		OrderJPA o=entman.find(OrderJPA.class,order.getId());
		o.setOrderstatus(os);
		
		entman.persist(o);
		entman.flush();
		}
	}

	@Override
	public int orders(CustomerJPA customer) {
		// TODO Auto-generated method stub
		int totalOrders=0;
		
		try
		{
		@SuppressWarnings("unchecked")
		Collection<OrderJPA> orders = entman.createQuery("FROM OrderJPA o WHERE o.customer = ?1").setParameter(1, customer).getResultList();

			for (Iterator<OrderJPA> iter = orders.iterator(); iter.hasNext();){
				OrderJPA order = (OrderJPA) iter.next();
				if (order.getOrderstatus().getOrderstatus().equals("Paid") || order.getOrderstatus().getOrderstatus().equals("Shipped")) 
				totalOrders= totalOrders + 1;
			}
			
		}catch (PersistenceException e) {
			System.out.println(e);
		} 
		return totalOrders;
	}	

	@Override
	public float amount(CustomerJPA customer) {
		// TODO Auto-generated method stub
		float totalAmount=0;
		
		try
		{
		@SuppressWarnings("unchecked")
		Collection<OrderJPA> orders = entman.createQuery("FROM OrderJPA o WHERE o.customer = ?1").setParameter(1, customer).getResultList();

		for (Iterator<OrderJPA> iter = orders.iterator(); iter.hasNext();){
				OrderJPA order = (OrderJPA) iter.next();
				if (order.getOrderstatus().getOrderstatus().equals("Paid") || order.getOrderstatus().getOrderstatus().equals("Shipped") ) 
				totalAmount = totalAmount + order.getTotalamount();
			}
			
		}catch (PersistenceException e) {
			System.out.println(e);
		} 
		return totalAmount;
	}

	@Override
	public Collection<?> showOrder(int idOrder) {
		// TODO Auto-generated method stub
		OrderJPA order =null;
		OrderdetailJPA orderdetail=null;
		
		try
		{
		@SuppressWarnings("unchecked")
		Collection<OrderJPA> orders = entman.createQuery("FROM OrderJPA o WHERE o.id = ?1").setParameter(1, idOrder).getResultList();

		TypedQuery<StatusJPA> query =  entman.createQuery("FROM StatusJPA s WHERE s.status = ?1", StatusJPA.class).setParameter(1, "Available");
		StatusJPA s=query.getSingleResult();
		
			for (Iterator<OrderJPA> iter = orders.iterator(); iter.hasNext();){
				order = (OrderJPA) iter.next();
			}
			
			for(Iterator<OrderdetailJPA> iter=order.getOrderdetail().iterator();iter.hasNext();){
				orderdetail=(OrderdetailJPA)iter.next();
				PetJPA pet=orderdetail.getPet();
				pet.setStatus(s);
				entman.merge(pet);
			}
		}catch (PersistenceException e) {
			System.out.println(e);
		} 	
		
		Collection<OrderdetailJPA> orderdlist= order.getOrderdetail();
		return orderdlist;

		
	}
}
